package github.ziwukun.jsonql.analysis;

import github.ziwukun.jsonql.lang.JSONQL;
import github.ziwukun.jsonql.lang.PropSort;
import github.ziwukun.jsonql.lang.Sort;
import github.ziwukun.jsonql.orm.FieldProp;
import github.ziwukun.jsonql.orm.Model;
import github.ziwukun.jsonql.orm.ModelProp;
import github.ziwukun.jsonql.orm.Prop;

/**
 * 排序语句检查
 * @author Hugo.Yu
 */
public class ModelAndSortAnalysistor implements ModelAndQLAnalysistor{
	
	@Override
	public void analysis(Model model, JSONQL ql) throws AnalysisException {
		Sort sort = ql.sort();
		if(sort != null) {
			analysisModelAndSort(model,sort);
		}
	}
	
	private void analysisModelAndSort(Model model,Sort sort) {
		for (PropSort propSort : sort.propSorts()) {
			Prop prop = model.getPropByName(propSort.prop());
			if(prop == null) {
				throw new AnalysisException("错误的@sort排序语句{}",sort.toJSONQL());
			}
			if(prop instanceof FieldProp) {
				if(!prop.sortable()) {
					throw new AnalysisException("错误的@sort排序语句{}",sort.toJSONQL());
				}
			}
			if(prop instanceof ModelProp) {
				if(!propSort.valIsSort() || propSort.valAsSort().isEmpty()) {
					throw new AnalysisException("错误的@sort排序语句{}",propSort.toJSONQL());
				}
				ModelProp modelProp = (ModelProp)prop;
				analysisModelAndSort(modelProp.propModel(),propSort.valAsSort());
			}
		}
	}
}
